/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Goal;

/**
 *
 * @author Djordje Gligorijevic
 */
public class DBBroker {

    Connection conn = null;
    String url = "jdbc:mysql://localhost:3306/";
    String dbName = "fonahp";
    String driver = "com.mysql.jdbc.Driver";
    String userName = "root";
    String password = "";

    private DBBroker() {
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
        } catch (InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
            Logger.getLogger(DBBroker.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void otvoriKonekciju() throws SQLException {
        conn = DriverManager.getConnection(url + dbName, userName, password);
    }

    public void zatvoriKonekciju() throws SQLException {
        conn.close();
    }

    public void unesiCilj(Goal goal) throws SQLException {
        String sql = "INSERT INTO goal VALUES (?,?,?)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setInt(1, goal.getId());
        ps.setString(2, goal.getName());
        ps.setString(3, goal.getDescription());
        ps.executeUpdate();

    }

    public void prikaziCilj(int id) throws Exception {
        String sql = "SELECT * FROM goal WHERE id=" + id;
        Statement st = conn.createStatement();
        ResultSet rs = st.executeQuery(sql);

        while (rs.next()) {
            Goal g = new Goal();
            g.setId(rs.getInt(1));
            g.setName(rs.getString(2));
            g.setDescription(rs.getString(3));
            System.out.println(g);
        }

    }

    public static DBBroker getInstance() {
        return DBBrokerHolder.INSTANCE;
    }

    private static class DBBrokerHolder {

        private static final DBBroker INSTANCE = new DBBroker();
    }
}
